package com.fnfn.sdk.api.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MySqlDBUtil extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(MySqlDBUtil.class);

    /**
     * @param userName 进入数据库所需要的用户名
     * @param password 进入数据库所需要的密码
     * @param savePath 数据库导出文件保存路径
     * @param databaseName 要导出的数据库名
     * @return 返回true表示备份成功，否则返回false
     */
    public static boolean backupDB(String userName, String password, String databaseName, String savePath) {
        try {
            String command = "mysqldump" + " -u" + userName + " -p" + password + " --set-charset=UTF8 " + databaseName
                    + " --ignore-table=" + databaseName + ".T_CCS_Sys_Back ";
            LOGGER.info("-----------backup command:{}", command);
            Process process = Runtime.getRuntime().exec(command);

            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(savePath), "utf8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            printWriter.close();
            bufferedReader.close();
            inputStreamReader.close();

            if (process.waitFor() == 0) {// 0 表示线程正常终止
                LOGGER.info("----------backup completed");
                process.destroy();
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("数据库备份失败", e);
        }
        return false;
    }

    /**
     * @param userName 数据库用户名
     * @param password 进入数据库所需要的密码
     * @param importFile 备份文件名
     * @param databaseName 要导入的数据库名
     * @return 返回true表示还原成功，否则返回false
     */
    public static boolean restoreDB(String userName, String password, String databaseName, String importFile) {
        try {
            String command = "mysql" + " -u" + userName + " -p" + password + " " + databaseName;
            LOGGER.info("-----------restore command:{}", command);
            Process process = Runtime.getRuntime().exec(command);

            OutputStream outputStream = process.getOutputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(importFile), "utf-8"));
            String str;
            StringBuilder sb = new StringBuilder();
            while ((str = br.readLine()) != null) {
                sb.append(str).append("\r\n");
            }
            str = sb.toString();
            OutputStreamWriter writer = new OutputStreamWriter(outputStream, "utf-8");
            writer.write(str);
            writer.flush();

            outputStream.close();
            br.close();
            writer.close();

            if (process.waitFor() == 0) {// 0 表示线程正常终止
                LOGGER.info("------------restore completed");
                process.destroy();
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("数据库还原失败", e);
        }
        return false;
    }
}
